﻿var WT3DModel;

function threeStart(_height) { // dataFunc 获取机柜，空调，墙等设备的json对象
    console.log("this.roomid", webapi.roomid)
    WT3DModel = new WT3D();   // 实例化 3D 核心对象，见 WT3D.core.js 文件。 
    var initOption = {
        antialias: true, // 启用平滑、抗锯齿效果
        loadSyn: false, // 是否启用异步加载
        showHelpGrid: false, // 是否显示网格线
        clearCoolr: 0x4068b0,  // 背景色
        clearColorOp: 0,    // 透明度
    }; 
    //初始化模型
    var models = [];
    //房间模型
    var buildData = webapi.getBuildData();
    roomConfig.buildData = buildData;
    console.log(' roomConfig', roomConfig)
    console.log(' buildData', buildData)
    if (buildData && buildData.roomConfig) {
        models = CreateRoomByJson(buildData.roomConfig, buildData.baseConfig);
    }
    if (buildData && buildData.baseConfig) {
        roomConfig.length = buildData.baseConfig.length;
        roomConfig.width = buildData.baseConfig.width;
        roomConfig.maxheight = buildData.baseConfig.maxheight;
        roomConfig.minheight = buildData.baseConfig.minheight;
        roomConfig.centerx = buildData.baseConfig.centerx;
        roomConfig.centerz = buildData.baseConfig.centerz;
        roomConfig.centerz = buildData.baseConfig.centerz;

        var scaleRate = 1;
        if (roomConfig.buildData.baseConfig && roomConfig.buildData.baseConfig.normRackSize) {
            scaleRate = roomConfig.buildData.baseConfig.normRackSize.width / 350;
        }

        roomConfig.cameraPostion.x = buildData.baseConfig.centerx / scaleRate ;
        roomConfig.cameraPostion.z = buildData.baseConfig.centerz*4 / scaleRate;
        roomConfig.cameraTarget.x = buildData.baseConfig.centerx / scaleRate;
        roomConfig.cameraTarget.z = buildData.baseConfig.centerz / scaleRate;
    }

    console.log(' roomConfig', roomConfig) 
    console.log(' buildData', buildData) 
    //机柜模型 
    if (buildData && buildData.racksConfig) {
        var rackmodels = createDevModels(buildData.racksConfig);
        models = models.concat(rackmodels);
    }
 
    //东环设备模型
    if (buildData && buildData.devConfig) {
        var devmodes = createDevModels(buildData.devConfig);
        console.log(devmodes)
        models = models.concat(devmodes);
    }
    //加载效果
    showLoading(
            models.length,//模型个数
            null,
            roomConfig.cameraPostion,
            roomConfig.cameraTarget,
            function () {//加载完成后回调
                modelBussiness = new ModelBussiness();
                modelBussiness.init();
                pageindex = new Page();
                pageindex.initPage();
                //旋转注册
                WT3DObj.mouseMoveRotateEvent = function (v) {
                    pageindex.transLeftBall(v);
                }
                //拓展功能
                WT3DObj.commonFunc.transToScreenCoord = function (point) {
                    var _this = WT3DObj; var screenCoord = {};
                    var vector = new THREE.Vector3(point.x, point.y, point.z);
                    vector.project(WT3DObj.camera);
                    screenCoord.x = (0.5 + vector.x / 2) * _this.width; screenCoord.y = (0.5 - vector.y / 2) * _this.height; return screenCoord;
                };
                WT3DObj.commonFunc.transToThreeCoord = function (x, y) { var _this = WT3DObj; var pX = (x / _this.width) * 2 - 1; var pY = -(y / _this.height) * 2 + 1; var p = new THREE.Vector3(pX, pY, -1).unproject(WT3DObj.camera); return p; };
            });
    var Aobjects = {  // 给3D对象绑定事件
        objects: models,
        Animation: [
            {
                obj_name: "",
                obj_animation: function (_obj) {

                },
                animationType: 0, // 动画类型 -1永久循环执行 0触发执行 >=1执行多少次
                aniInterval: 1000, // 执行时间间隔 毫秒
            }],
        events: {

            dbclick: [
                {
                    obj_name: "ALL",
                    obj_event: function (_obj, face) { // 被选中的对象 被选中的面
                        // 此处设置双击聚焦
                        {
                         
                            modelBussiness.dbClickSelect(_obj, face);
                            if (_obj.name.indexOf("_LightCubeBorder") >= 0) {
                                _obj = WT3DObj.commonFunc.findObject(_obj.name.replace("_LightCubeBorderLight", "").replace("_LightCubeBorder", ""));
                            }
                            var info = getRelationInfoByModelId(_obj.name);
                            if (info && ( (webapi.OtherDevsCache && webapi.OtherDevsCache.Modelobjs["m_" + _obj.name]) || webapi.CabInfosCache.Modelobjs["m_" + _obj.name])) {
                                modelBussiness.commonFunc.ZoomINShow(_obj);
                            }

                        }
                    }
                },
            ],
          mouseDown: [
              {
                  obj_name: "ALL",
                    obj_event: function (_obj, face, objs, event) { // 被选中的对象 被选中的面
                      if (event.button == 0) {
                      modelBussiness.clickSelectCabinet(_obj, face, objs);
                      }
                      if (event.type == "touchstart") {
                          modelBussiness.touchStart(objs[0].object);
                      }
                  }
              },
            ],
            mouseMove: [
                {
                    obj_name: "ALL",
                    obj_event: function (_obj) {
                    console.log(_obj.name);
                    return true;//返回true表示移动
                }
            },
            ]
        },
        //WT3DModel.viewState;表示0编辑状态 1表示运行状态
        btns: []
    }


    if (parent != null && parent.Aobjects_objects != null) {
        Aobjects.objects = parent.Aobjects_objects;
    }
	
	// 温度信息	

	// httpGetSyn(webapi.serverHead +   `/business/cmdb/roomorrack/getTemperatures`, function(response) {
	httpGetSyn('../dataDemo/tempTureData.json', function(response) {
		console.log(response)
		if (response && response.data) {
			let data = []
			data = response.data
			sessionStorage.setItem('temperatures',JSON.stringify(data) )
		}
	}, function(err) {
		console.log(err);
	});
	
    //修改btns

    //优化Aobjects 此处用于优化 可以先异步加载图片
    /*
   [
   {
   imgurl: "../img/3dImg/floor.jpg",
   width: 128,
   height: 128,
   },
   {
   imgurl:"../img/3dImg/floor.jpg",
   },
   ]
   */
    Aobjects.imageList = [];
    imageUUIDList = [];
    //遍历获取图片资源
    function getImageList(obj) {
        if (obj && typeof (obj) == "object") {
            // console.log('img',obj)
            $.each(obj, function (_index, _obj) {
                if (_obj && _obj.imgurl) {
                    var imgObj = {};
                    imgObj.uuid = _obj.imgurl;
                    imgObj.imgurl = _obj.imgurl;
                    if ($.inArray(imgObj.uuid, imageUUIDList) < 0) {
                        imageUUIDList.push(imgObj.uuid);
                        Aobjects.imageList.push(imgObj);
                    }
                }
                getImageList(_obj);
            });
        }
    }
    getImageList(Aobjects.objects);
    if (_height != null && typeof (_height) != 'undefined' && _height == 0) {
        $("#canvas-frame").height($(document).height());
    }
    //检查是否存在动态资源需要加载
    var dynamicSource = [];
    $.each(Aobjects.objects, function (_index, _obj) {
        /*
        动态资源结构
        {
               name: '',
               objType: 'dynamicSource',
               file:"";
               loadedCallBackFuncName:""
           }
        */
        if (_obj && _obj.objType && _obj.objType == "dynamicSource") {
            dynamicSource.push(_obj);
        }
    });
    if (dynamicSource.length > 0) {
        WT3DModel.additionModels = {};
        var loadednub = 0;
        $.each(dynamicSource, function (_index, _obj) {
            $.getScript(_obj.file).done(function () {
                /* 耶，没有问题，这里可以干点什么 */
                loadednub++;
                if (loadednub == dynamicSource.length) {
                    $.each(dynamicSource, function (_dindex, _dobj) {
                        if (_dobj.loadedCallBackFuncName && _dobj.loadedCallBackFuncName != "") {
                            eval(_dobj.loadedCallBackFuncName + "()");
                        }
                    });
                }
            })
                .fail(function () {
                    /* 靠，马上执行挽救操作 */
                    console.log("文件加载失败");
                });
        });
    }

    WT3DModel.initWT3D('canvas-frame', initOption, Aobjects);
    WT3DModel.start();
}
